package nio02;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

public class SelectSockets {

    public static int PORT_NUMBER = 11111;

    public static void main(String[] args) throws Exception {
        new SelectSockets().go(args);
    }

    public void go(String[] args) throws Exception {

        int port = PORT_NUMBER;

        if (args.length > 0) {
            port = Integer.parseInt(args[0], 10);
        }

        System.out.println("Listening on port " + port);

        // Allocate an unbound server socket channel
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        // Get the associated ServerSocket to bind it with
        ServerSocket serverSocket = serverChannel.socket();

        // Create a new Selector for user below
        Selector selector = Selector.open();

        // Set the port the server channel will listen to
        serverSocket.bind(new InetSocketAddress(port));

        // Set noblocking mode fro the listening socket
        serverChannel.configureBlocking(false);

        // Register the ServerSocketChannel with the Selector
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);


        while (true) {
            // This may block for a long time .
            // selected set contains keys of
            int n = selector.select();

            if (n == 0) {
                continue; // nothing
            }

            Iterator it = selector.selectedKeys().iterator();

            // Look at each key in the selected set
            // hello
            // Look at each key in the selected set


        }



    }

}
